<template>
  <div class="loginFrame">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>订餐出餐系统</h2>
          <p>前台登录</p>
        </div>
      </template>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        @keyup.enter="handleLogin"
      >
        <div>
          <label class="label">账号</label>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入账号(5-16位非空字符)"
              prefix-icon="User"
              clearable
              size="large"
            />
          </el-form-item>
        </div>

        <div>
          <label class="label">密码</label>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码(5-16位非空字符)"
              prefix-icon="Lock"
              show-password
              clearable
              size="large"
            />
          </el-form-item>
        </div>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            style="width: 100%; margin-top: 20px"
            size="large"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer">
        <el-link @click="goToRegister" type="primary" underline="never" class="footer-link">没有账号?点击注册</el-link>
        <el-link @click="goToForgetPassword" type="primary" underline="never" class="footer-link">忘记密码?</el-link>
      </div>
    </el-card>
  </div>
</template>

<script lang="js" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import router from '@/router'
import axios from 'axios'

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则（与后端保持一致：5-16位非空字符）
const loginRules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { 
      pattern: /^\S{5,16}$/,
      message: '长度在5到16个字符且不能包含空格', 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      pattern: /^\S{5,16}$/,
      message: '长度在5到16个字符且不能包含空格', 
      trigger: 'blur' 
    }
  ]
})

const loading = ref(false)
const loginFormRef = ref()

// 登录方法
const handleLogin = async () => {
  try {
    // 验证表单
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    // 使用URLSearchParams构造表单数据
    const formData = new URLSearchParams()
    formData.append('username', loginForm.username)
    formData.append('password', loginForm.password)

    const response = await axios.post('http://localhost:8081/user/login', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    
    // 处理响应
    if (response.data && response.data.code === 200) {
      console.log(response);
      localStorage.setItem('user', response.data.data)
      localStorage.setItem('userId', response.data.data.userId)
      ElMessage.success('登录成功')
      router.push('/front/layout')
    } else {
      ElMessage.error(response.data.msg || '登录失败')
    }
  } catch (error) {
    // 错误处理
    if (error.response) {
      const msg = error.response.data.msg || error.response.data.message || '登录失败'
      ElMessage.error(msg)
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('请求出错，请稍后再试')
    }
    console.error('登录错误:', error)
  } finally {
    loading.value = false
  }
}

// 去注册
const goToRegister = () => {
  router.push('/front/register')
}

// 去忘记密码
const goToForgetPassword = () => {
  router.push('/front/forget')
}
</script>

<style scoped>
.loginFrame {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 16px;
  background-color: #f5f7fa;
  background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
  box-sizing: border-box;
}

.login-card {
  width: 100%;
  max-width: 400px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  padding: 16px 0;
}

.card-header h2 {
  margin-bottom: 8px;
  color: #409eff;
  font-size: 24px;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

.footer {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin: 20px 0;
}

.footer-link {
  font-size: 14px;
  padding: 8px 0;
  text-align: center;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

/* 移动端优化 */
@media (max-width: 480px) {
  .login-card {
    border-radius: 0;
    box-shadow: none;
    border: none;
    background: transparent;
  }
  
  .card-header h2 {
    font-size: 22px;
  }
  
  .card-header p {
    font-size: 15px;
  }
  
  :deep(.el-input__wrapper) {
    padding: 4px 15px;
    height: 48px;
  }
  
  :deep(.el-button) {
    height: 48px;
    font-size: 16px;
  }
}

/* 防止移动端键盘弹出时页面变形 */
@media (max-height: 500px) {
  .loginFrame {
    align-items: flex-start;
    padding-top: 20px;
  }
}
</style>